// Package lockUtils
// @File: localLock.go
// @Description:
// @Author: YaoRuiQi
// @Date: 2025/8/29 14:03

package localLock

import (
	"sync"
	"time"
)

type LocalLockManager struct {
	lockMap sync.Map
	cleaner time.Ticker
}

var LocalLock *LocalLockManager

func InitLocalLock(cleanTicker time.Ticker) {
	LocalLock = &LocalLockManager{
		cleaner: cleanTicker,
	}
}

func (l *LocalLockManager) Lock(key string, waitTime time.Duration) (*Mutex, error) {
	lockInterface, _ := l.lockMap.LoadOrStore(key, NewMutex())
	mutexLock := lockInterface.(*Mutex)

	if err := mutexLock.TryLockWithTimeout(waitTime); err != nil {
		return nil, err
	} else {
		return mutexLock, nil
	}
}

func (l *LocalLockManager) UnLock(lock *Mutex) error {
	return lock.UnLock()
}
